import Vue from 'vue'
import VueRouter from 'vue-router'
import Home from '../components/Home.vue'
import Login from '../components/Login.vue'
import Welcome from '../components/Welcome.vue'
import Users from '../components/user/Users.vue'
import List from '../components/goods/List.vue'
import OrderList from '../components/order/OrderList.vue'
import Logs from '../components/loginlogs/Logs.vue'

Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    redirect: '/home'
  },
  {
    path: '/login',
    name: 'Login',
    component: Login
  },
  {
    path: '/home',
    name: 'Home',
    component: Home,
    redirect: '/welcome',
    children: [
      {
        path: '/welcome',
        component: Welcome
      },
      {
        path: '/user',
        component: Users
      },
      {
        path: '/goodslist',
        component: List
      },
      {
        path: '/orders',
        component: OrderList
      },
      {
        path: '/logs',
        component: Logs
      },
    ]
  }
]

const router = new VueRouter({
  routes
})
// 挂载全局路由守卫
router.beforeEach(async (to, from, next) => {
  // to 将要访问的路径
  // from 代表从哪个路径跳转而来
  // next 是一个函数，表示放行
  // next() 放行 next('/login') 强制跳转
  if (to.path.startsWith('/login')) return next();
  // 获取token
  const tokenStr = sessionStorage.getItem('token')
  if (!tokenStr) return next('/login')
  const { data: res } = await router.app.$http.get('/api/users/verify', {
    params:
    {
      user_name: sessionStorage.getItem('username')
    },
    headers: { authorization: tokenStr }
  })
  if (res.code !== 1) return next('/login')
  if (to.path == '/login') return next('/home')
  next()
})

export default router
